from flask import Blueprint, request, jsonify
from app import db, jwt
from app.models.vital_signs import VitalSigns
from flask_jwt_extended import jwt_required, get_jwt_identity

bp = Blueprint('vital_signs', __name__, url_prefix='/api/vital-signs')

@bp.route('', methods=['POST'])
@jwt_required()
def create_vital_signs():
    """创建生命体征记录"""
    try:
        user_id = get_jwt_identity()
        data = request.get_json()
        
        # 创建记录
        vital_signs = VitalSigns(
            user_id=user_id,
            heart_rate=data.get('heart_rate'),
            blood_pressure_systolic=data.get('blood_pressure_systolic'),
            blood_pressure_diastolic=data.get('blood_pressure_diastolic'),
            respiratory_rate=data.get('respiratory_rate'),
            blood_oxygen=data.get('blood_oxygen'),
            body_temperature=data.get('body_temperature')
        )
        
        db.session.add(vital_signs)
        db.session.commit()
        
        return jsonify({
            'message': '生命体征记录创建成功',
            'data': vital_signs.to_dict()
        }), 201
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@bp.route('', methods=['GET'])
@jwt_required()
def get_vital_signs():
    """获取用户的全部生命体征记录"""
    try:
        user_id = get_jwt_identity()
        vital_signs = VitalSigns.query.filter_by(user_id=user_id).order_by(VitalSigns.record_date.desc()).all()
        
        return jsonify({
            'data': [record.to_dict() for record in vital_signs]
        }), 200
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@bp.route('/<int:record_id>', methods=['GET'])
@jwt_required()
def get_vital_signs_by_id(record_id):
    """获取特定生命体征记录"""
    try:
        user_id = get_jwt_identity()
        vital_signs = VitalSigns.query.filter_by(id=record_id, user_id=user_id).first()
        
        if not vital_signs:
            return jsonify({'error': '记录不存在'}), 404
            
        return jsonify({
            'data': vital_signs.to_dict()
        }), 200
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@bp.route('/<int:record_id>', methods=['PUT'])
@jwt_required()
def update_vital_signs(record_id):
    """更新生命体征记录"""
    try:
        user_id = get_jwt_identity()
        vital_signs = VitalSigns.query.filter_by(id=record_id, user_id=user_id).first()
        
        if not vital_signs:
            return jsonify({'error': '记录不存在'}), 404
        
        data = request.get_json()
        
        # 更新字段
        update_fields = [
            'heart_rate', 'blood_pressure_systolic', 'blood_pressure_diastolic',
            'respiratory_rate', 'blood_oxygen', 'body_temperature'
        ]
        
        for field in update_fields:
            if field in data:
                setattr(vital_signs, field, data[field])
        
        db.session.commit()
        
        return jsonify({
            'message': '生命体征记录更新成功',
            'data': vital_signs.to_dict()
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@bp.route('/<int:record_id>', methods=['DELETE'])
@jwt_required()
def delete_vital_signs(record_id):
    """删除生命体征记录"""
    try:
        user_id = get_jwt_identity()
        vital_signs = VitalSigns.query.filter_by(id=record_id, user_id=user_id).first()
        
        if not vital_signs:
            return jsonify({'error': '记录不存在'}), 404
        
        db.session.delete(vital_signs)
        db.session.commit()
        
        return jsonify({
            'message': '生命体征记录删除成功'
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500